package com.hnn;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hnn
 * @version 1.0
 * @date 2024-03-21 08:58
 */
public class BioSocketServer {

    private static void process(Socket client) {
        System.out.printf("-----%s已连接%n", client.getRemoteSocketAddress());
        byte[] buff = new byte[4096];
        InputStream is = null;
        OutputStreamWriter osw = null;
        try {
            is = client.getInputStream();
            osw = new OutputStreamWriter(client.getOutputStream());
            while (true) {
                int r = is.read(buff, 0, buff.length);
                if (r > 0) {
                    String receive = new String(buff, 0, r);
                    System.out.printf("------->接收:%s%n", receive);

                    osw.write(receive + " hello");
                    osw.flush();
                } else {
                    System.out.println("close:" + r);
                    break;
                }
            }
        } catch (Exception e) {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException ex) {

                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException ex) {

                }
            }
        }

    }

    public static void main(String[] args) throws IOException {
        ExecutorService es = Executors.newFixedThreadPool(4);
        ServerSocket server = new ServerSocket(17777);
        while (true) {
            final Socket client = server.accept();
            es.execute(new Runnable() {
                @Override
                public void run() {
                    process(client);
                }
            });
        }
    }
}
